package org.wicket.jbpm.engine.handlers;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.taskmgmt.exe.Assignable;
import org.springframework.beans.factory.BeanFactory;
import org.wicket.jbpm.engine.exception.WicketJbpmException;
import org.wicket.jbpm.engine.utils.AddJbpmUsers;
import org.wicket.jbpm.model.UserGroup;
import org.wicket.jbpm.service.group.UserGroupService;
import org.wicket.jbpm.service.user.UserService;

public class AssignmentAction extends SpringAssignmentHandler
{

    private static final Log log = LogFactory.getLog(AssignmentAction.class);
    /**
	 * 
	 */
    private static final long serialVersionUID = -4947986069845798768L;
    private UserService userService;
    private UserGroupService userGroupService;

    private Element groupActor;
    private Element actors;

    @Override
    protected void initialiseHandler(BeanFactory factory)
    {
	userService = (UserService) factory.getBean("userService");
	userGroupService = (UserGroupService) factory
		.getBean("userGroupService");
    }

    public void assign(Assignable assignable, ExecutionContext executionContext)
	    throws Exception
    {

	final List<String> groupOfUsers = new ArrayList<String>();
	String[] assignedPooledActors = null;

	if (groupActor == null && actors == null)
	{
	    throw new WicketJbpmException(
		    "must assign an actors/groupActor for particular task.");
	}

	if (groupActor != null
		&& StringUtils.isNotBlank(groupActor.getTextTrim()))
	{

	    final String[] grps = StringUtils.split(groupActor.getTextTrim(),
		    ',');

	    if (grps != null)
	    {
		for (int i = 0; i < grps.length; i++)
		{
		    final UserGroup userGroup = userGroupService
			    .findByDscp(grps[i]);
		    if (userGroup == null)
		    {
			throw new WicketJbpmException(
				"The addressee doesn't exist on the UserGroup");
		    }
		    final List<String> grpUsr = userService
			    .findForJbpmUser(userGroup.getId());
		    AddJbpmUsers.addUserInList(grpUsr, groupOfUsers);
		}
	    }
	}

	if (actors != null && StringUtils.isNotBlank(actors.getTextTrim()))
	{
	    final String[] users = StringUtils.split(actors.getTextTrim(), ',');
	    final List<String> usrlist = new ArrayList<String>();
	    if (users != null)
	    {
		for (int i = 0; i < users.length; i++)
		{
		    usrlist.add(users[i]);
		}
		AddJbpmUsers.addUserInList(usrlist, groupOfUsers);
	    }
	}

	log.info("worflow users: " + groupOfUsers);

	assignedPooledActors = AddJbpmUsers.getGroupUsers(groupOfUsers
		.toArray());

	if (assignedPooledActors != null)
	{
	    assignable.setPooledActors(assignedPooledActors);
	}
    }

}
